<template>
  <div class="product_manage">
    <el-row>
      <el-col :span="2" :offset="22">
        <el-button icon="el-icon-plus" type="primary" @click="toAddProduct()">新增产品模板</el-button>
      </el-col>
    </el-row>
    <el-table
      :data="productList"
      size="mini"
      :height="getTableHeight()"
      style="width: 100%"
      row-key="templateId"
      :expand-row-keys="expandRowKeys"
    >
      <el-table-column type="expand">
        <template slot-scope="scope">
          <product-variant-list
            :product="scope.row"
            v-on:refresh="updateByProductVariant"
            v-on:modify="showModifyProductVariant"
          />
        </template>
      </el-table-column>
      <el-table-column prop="name" label="产品名称"></el-table-column>
      <el-table-column label="是否上架">
        <template slot-scope="scope">{{scope.row.status === productSaleStatus.ONLINE ?'已上架':'未上架'}}</template>
      </el-table-column>
      <el-table-column prop="descPrice" label="价格区间"></el-table-column>
      <el-table-column prop="catalogName" label="业务范围"></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            type="text"
            size="small"
            @click="setProductSaleStatus(scope.row)"
          >{{scope.row.status === 'ONLINE'?'下架':'上架'}}</el-button>
          <el-button type="text" size="small" @click="toModify(scope.row)">修改</el-button>
          <el-button type="text" size="small" @click="newProductVariant(scope.row)">新增变种产品</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog :title="dialogTitle" :visible.sync="showModifyDialog" width="80%" top="5vh">
      <el-form ref="form" :model="form" label-width="80px">
        <div class="info-sec">
          <div class="title">
            <span class="fa fa-address-book-o">&nbsp;</span>基本信息
          </div>
          <div class="content">
            <div class="sub-info-sec">
              <div class="sub-content">
                <div class="row-block" style="display: flex">
                  <el-form-item
                    prop="name"
                    label="产品名称"
                    :rules="[{required:true,message:'请输入产品名称'}]"
                  >
                    <el-input placeholder="请输入" v-model="form.name"></el-input>
                  </el-form-item>
                  <el-form-item
                    prop="catalogId"
                    label="业务范围"
                    :rules="[{required:true,message:'用户名不能为空'}]"
                  >
                    <el-select
                      v-model="form.catalogName"
                      placeholder="请选择业务范围"
                      @change="selectCatalogue()"
                    >
                      <el-option
                        v-for="catalogue in productCatalogue"
                        :key="catalogue[0]"
                        :label="catalogue[1]"
                        :value="catalogue[1]"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </div>
                <div class="row-block" style="display: flex;">
                  <el-form-item
                    prop="description"
                    label="产品描述"
                    :rules="[{required:true,message:'请输入产品描述'}]"
                  >
                    <el-input placeholder="请输入" v-model="form.description"></el-input>
                  </el-form-item>
                  <el-form-item
                    prop="descPrice"
                    label="价格描述"
                    :rules="[{required:true,message:'请输入价格描述'}]"
                  >
                    <el-input placeholder="请输入" v-model="form.descPrice"></el-input>
                  </el-form-item>
                </div>
                <!-- <div class="row-block" style="display: flex">
                  <el-form-item
                    label="价格范围"
                    prop="priceType"
                    :rules="[{required:true,message:'请选择价格类型'}]"
                  >
                    <template>
                      <el-radio
                        v-model="form.priceType"
                        :label="priceType.FLOAT.val"
                      >{{priceType.FLOAT.desc}}</el-radio>
                      <el-radio
                        v-model="form.priceType"
                        :label="priceType.FIXED.val"
                      >{{priceType.FIXED.desc}}</el-radio>
                    </template>
                  </el-form-item>
                  <el-form-item
                    prop="price"
                    label="价格"
                    v-if="form.priceType===priceType.FIXED.val"
                    :rules="[{required:true,message:'请输入价格'}]"
                  >
                    <el-input type="number" placeholder="请输入" v-model="form.price"></el-input>
                  </el-form-item>
                </div>
                -->
                <div class="row-block" style="display: flex;display:-webkit-flex;">
                  <el-form-item
                    label="客户推广积分描述"
                    prop="cusCreditDesc"
                    label-width="130px"
                    :rules="[{required:true,message:'请输入客户推广积分描述'}]"
                    style="flex:1;-webkit-flex:1"
                  >
                    <el-input placeholder="请输入" v-model="form.cusCreditDesc"></el-input>
                  </el-form-item>
                  <el-form-item
                    prop="empCreditDesc"
                    label-width="130px"
                    style="flex:1;-webkit-flex:1"
                    label="业务员积分描述"
                    :rules="[{required:true,message:'请输入业务员积分描述'}]"
                  >
                    <el-input placeholder="请输入" v-model="form.empCreditDesc"></el-input>
                  </el-form-item>
                </div>
              </div>
            </div>
          </div>
        </div>
        <!--<div class="info-sec">-->
        <!--<div class="title"><span class="fa fa-address-book-o">&nbsp;</span>产品缩略图</div>-->
        <!--<div class="content">-->
        <!--</div>-->
        <!--</div>-->
        <div class="info-sec">
          <div class="title">
            <span class="fa fa-address-book-o">&nbsp;</span>其他信息
          </div>
          <div class="content">
            <div class="row-block-img" style="display: flex">
              <el-form-item
                prop="titleImage"
                label="产品图片"
                :rules="[{required:true,message:'请选择产品图片'}]"
              >
                <el-upload
                  class="avatar-uploader"
                  :action="imageUploadUrl"
                  :show-file-list="false"
                  :on-success="handleUploadProductImageSuccess"
                  :before-upload="beforeImageUpload"
                >
                  <img v-if="productImageUrl" :src="productImageUrl" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
                <el-input type="hidden" v-model="form.titleImage"></el-input>
              </el-form-item>
              <el-form-item
                prop="descImage"
                label="产品详情图片"
                :rules="[{required:true,message:'请选择产品详情图片'}]"
              >
                <el-upload
                  class="avatar-uploader"
                  :action="imageUploadUrl"
                  :show-file-list="false"
                  :on-success="handleUploadProductDetailImageSuccess"
                  :before-upload="beforeImageUpload"
                >
                  <img v-if="productDetailImageUrl" :src="productDetailImageUrl" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
                <el-input type="hidden" v-model="form.descImage"></el-input>
              </el-form-item>
            </div>
          </div>
        </div>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showModifyDialog = false">取消</el-button>
        <el-button type="primary" @click="dialogTitle === '修改产品'?modifyProduct():addProduct()">确定</el-button>
      </span>
    </el-dialog>
    <product-variant-modify
      :product="currentProduct"
      :variant="currentVariant"
      :show.sync="showProductVariantDialog"
      :status="modifyStatus"
      @success="fetchProductList()"
    ></product-variant-modify>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex'
import {
  PRICE_TYPE,
  PRODUCT_SALE_STATUS,
  SUCCESS_CODE,
  OP_SUCCESS,
  OP_FAIL,
  BACKEND_URL
} from '@/config/config'
import ProductVariantModify from '@/views/product-manage/product_variant_modify'
import ProductVariantList from '@/views/product-manage/product_variant_list'

export default {
  name: 'product_manage',
  components: { ProductVariantModify, ProductVariantList },
  data: function() {
    return {
      modifyStatus: 'NEW',
      expandRowKeys: [], // 指定展开行
      imageUploadUrl: `${BACKEND_URL}/api/upload/img/product`, // 图片上传地址
      showModifyDialog: false,
      dialogTitle: '',
      title: '产品管理',
      selectedProduct: {},
      priceType: PRICE_TYPE,
      productSaleStatus: PRODUCT_SALE_STATUS,
      selectedProductCatalogueId: null,
      form: {
        catalogId: 0,
        catalogName: '',
        creditType: '',
        descImage: '',
        descPrice: 's',
        id: 0,
        name: '',
        cusCreditDesc: '',
        empCreditDesc: '',
        status: '',
        titleImage: '',
        description: ''
        // productImage: null, // 产品缩略图
        // productDetailImage: null
      },
      productImageUrl: '',
      productDetailImageUrl: '',
      showProductVariantDialog: false,
      currentProduct: null,
      currentVariant: null
    }
  },
  computed: {
    ...mapState('productManage', [
      'productList',
      'selected',
      'search',
      'productCatalogue'
    ])
  },
  methods: {
    ...mapActions('productManage', [
      'fetchProductList',
      'updateProduct',
      'newProduct',
      'setSaleStatus'
    ]),
    newProductVariant(product) {
      this.modifyStatus = 'NEW'
      this.currentProduct = product
      this.showProductVariantDialog = true
    },
    showModifyProductVariant(data) {
      let { product, variant } = data
      this.currentProduct = product
      this.currentVariant = variant
      this.showProductVariantDialog = true
      this.modifyStatus = 'MODIFY'
    },
    toModify(selectedProduct) {
      this.dialogTitle = '修改产品'
      this.showModifyDialog = true
      this.form = selectedProduct
      this.productImageUrl = selectedProduct.titleImage
      this.productDetailImageUrl = selectedProduct.descImage
      this.form.descImage = this.form.descImage.split('/').pop()
      this.form.titleImage = this.form.titleImage.split('/').pop()
    },
    toAddProduct() {
      this.dialogTitle = '新增产品模板'
      this.showModifyDialog = true
      this.form = {}
      this.productDetailImageUrl = null
      this.productImageUrl = null
    },
    handleUploadProductImageSuccess(res, file) {
      this.form.titleImage = res.data.fileName
      this.productImageUrl = URL.createObjectURL(file.raw)
    },
    beforeImageUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2
      return true
    },
    handleUploadProductDetailImageSuccess(res, file) {
      this.form.descImage = res.data.fileName
      this.productDetailImageUrl = URL.createObjectURL(file.raw)
    },
    selectCatalogue(val) {
      let catalogueName = this.form.catalogName
      for (let catalogue of this.productCatalogue) {
        if (catalogue[1] === catalogueName) {
          this.form.catalogId = catalogue[0]
          break
        }
      }
      console.log(val)
    },
    /**
     * 修改产品
     */
    modifyProduct() {
      console.log(this.form)
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (!this.form.price) this.form.price = 0
          this.updateProduct(this.form).then(result => {
            this.showModifyDialog = false
            if (result.status === SUCCESS_CODE) {
              this.fetchProductList()
              this.$swal(OP_SUCCESS, '', 'success')
            } else {
              this.$swal(OP_FAIL, '', 'error')
            }
          })
        }
      })
    },
    /**
     * 新增产品
     */
    addProduct() {
      this.$refs['form'].validate((valid, b, c, d) => {
        if (valid) {
          if (!this.form.price) this.form.price = 0
          let newProductData = {}
          Object.assign(newProductData, this.form, { creditType: 'NONE' })
          this.newProduct(newProductData).then(result => {
            this.showModifyDialog = false
            if (result.status === SUCCESS_CODE) {
              this.fetchProductList()
              this.$swal(OP_SUCCESS, '', 'success')
            } else {
              this.$swal(OP_FAIL, '', 'error')
            }
          })
        }
      })
    },
    /**
     * 修改产品上下架状态
     */
    setProductSaleStatus(product) {
      let tip =
        product.status === this.productSaleStatus.ONLINE ? '下架' : '上架'
      this.$swal(
        `${product.name}`,
        `你确定要${tip}该产品吗？`,
        'question'
      ).then(result => {
        if (result) {
          let newStatus =
            product.status === this.productSaleStatus.ONLINE
              ? this.productSaleStatus.OFFLINE
              : this.productSaleStatus.ONLINE
          this.setSaleStatus({ id: product.templateId, status: newStatus }).then(
            result => {
              if (result.status === SUCCESS_CODE) {
                this.fetchProductList()
                this.$swal(OP_SUCCESS, '', 'success')
              } else {
                this.$swal(OP_FAIL, '', 'error')
              }
            }
          )
        }
      })
    },
    updateByProductVariant(key) {
      // this.expandRowKeys.length = 0
      // this.expandRowKeys.push(key)
      this.fetchProductList()
    }
  },
  created() {
    this.fetchProductList()
  }
}
</script>
<style lang="stylus">
.info-sec {
  display: flex;
  border-bottom: 1px solid #e8e8e8;
  padding-bottom: 5px;
  margin: 10px 0;
}

.info-sec .row-block .el-form-item:first-child {
  /* flex: 2; */
}

.info-sec .row-block .el-form-item:last-child {
  /* flex: 1; */
}

.info-sec .el-form-item {
  margin-right: 22px;
}

.info-sec .title {
  flex: 1;
  font-size: 18px;
  margin: 5px;
}

.info-sec .content {
  flex: 4;
}

.info-sec .title span:first-child:before {
  min-width: 20px;
  display: inline-block;
  text-align: center;
}

.info-sec .content .sub-info-sec {
  display: flex;
  width: inherit;
  margin: 5px;
}

.info-sec .content .sub-info-sec .sub-title {
  flex: 1;
  font-size: 15px;
  max-width: 100px;
}

.info-sec .content .sub-info-sec .sub-content {
  flex: 3;
}

.info-sec .content .sub-info-sec .id-card-image {
  width: 70%;
  margin: 5px;
  border-bottom: 1px solid #e8e8e8;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 200px;
  height: 111px;
  line-height: 111px;
  text-align: center;
}

.avatar {
  width: 200px;
  min-height: 111px;
  display: block;
}

.product_manage .el-dialog__body {
  height: 70vh;
  overflow: auto;
}

.el-form-item__label {
  text-align: left;
}
</style>
